// pages/order/order.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc()
Page({

  // 顶部tab栏切换
  TabOrder(e) {
    // 重置orderList
    var index = e.currentTarget.dataset.index;
    this.setData({
      index,
      orderList: [], //重置
      page: 1 //默认拉取第一页
    })
    if (this.data.sort) {
      this.getOrderList(index, this.data.sort);
    } else {
      this.getOrderList(index, 'orderlist');
    }

  },
  /**
   * 页面的初始数据
   */
  data: {
    index: 50,
    page: 1, //默认第一页,
    orderList: [],
    sort: ''
  },
  /**
   * 申请发货
   */
  showSales(e) {
    console.log(e)
    let order_id = e.currentTarget.dataset.order_id
    pulibc.navigateUrl('../order-details/order-details?order_id=' + order_id)
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    // 初始化列表
   this.setData({orderList:[]})
    if (options.index || options.sort) {
      let index = options.index;
      let sort = options.sort;
      this.setData({
        index,
        sort
      })
    } else {
      this.getOrderList(50, 'orderlist');
    }
  },
  // 取消订单
  cancelOrderTap(e) {
    let order_id = e.currentTarget.dataset.order_id;
    let url = apiurl + '/order/cancelOrder';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.order_id = order_id;
    wx.request({
      url: url,
      data: params,
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: res => {
        pulibc.showToast('订单已取消', 'none');
        let orderList = this.data.orderList;
        orderList.map((item, index) => {
          if (item.order_id == order_id) {
            orderList.splice(index, 1)
          }
        })
        this.setData({
          orderList
        })
      }
    })


  },
  // 获取订单列表
  getOrderList(index, sort) {
    wx.showLoading({
      title: '加载中',
    })
    let url = apiurl + '/order/' + sort;
    let params = {};
    params.key = wx.getStorageSync('key');
    params.page = this.data.page;
    params.type = index;
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)
        if (res.data.code == 200) {
          let orderList = res.data.datas.list;
          // 拼接数组
          orderList = this.data.orderList.concat(orderList)
          this.setData({
            orderList
          })
          // 隐藏loading
          wx.hideLoading();
          console.log("orderList", this.data.orderList)
        }else if(res.data.code == 400){
          pulibc.navigateUrl('../register/register')
        }
        

      }
    })
  },
  // 物流详情
  toLogisticsDetail(e) {
    console.log(e)
    var order_id = e.currentTarget.dataset.order_id;
    pulibc.navigateUrl('/pages/logistics-detail/logistics-detail?order_id=' + order_id);
  },
  //支付 调用微信接口
  toPayTap(e) {
    console.log("paysn", e.currentTarget.dataset.pay_sn)
    let pay_sn = e.currentTarget.dataset.pay_sn;
    let url = apiurl + '/memberpayment/pay_new';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.pay_sn = pay_sn;
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)
        if (res.data.code == 200) {
          // 发起微信支付
          wx.requestPayment({
            timeStamp: res.data.datas.wx.timeStamp,
            nonceStr: res.data.datas.wx.nonceStr,
            package: res.data.datas.wx.package,
            signType: res.data.datas.wx.signType,
            paySign: res.data.datas.wx.paySign,
            appId: res.data.datas.wx.appId,
            fail: (error) => {
              console.log("pay_err", JSON.stringify(error))
              // if (error.errMsg.indexOf('cancel')!=-1){
              //  pulibc.showToast('支付失败','none')
              // }

            },
            success: () => {
              wx.showToast({
                title: '支付成功'
              })
              // 支付成功跳转到待发货页面
              if (this.data.sort) {
                this.getOrderList(20, this.data.sort);
              } else {
                this.getOrderList(20, 'orderlist');
              }
            }
          })
        } else {

        }

      }
    })
  },
  // 订单详情
  showOrderDetails(e) {
    let order_id = e.currentTarget.dataset.order_id
    pulibc.navigateUrl('../order-details/order-details?order_id=' + order_id)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }else {
      // 初始化列表
      this.setData({ orderList: [] })
      let index = this.data.index;
      let sort = this.data.sort;
   
      if (index || sort){
        this.getOrderList(index, sort);
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    // 实现下拉加载更多数据
    let index = this.data.index;
    let sort = this.data.sort ? this.data.sort : 'orderlist';
    let page = this.data.page;
    if (this.data.orderList.length == parseInt(page + '0')) {
      page++;
      this.setData({
        page
      });
      this.getOrderList(index, sort);
      wx.showLoading({
        title: '加载中',
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})